package com.boot.security.model.bo;

import com.boot.security.model.vo.AccountInfo;
import com.boot.security.model.vo.WebDetail;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description Token 和缓存中用的验证消息
 * @date 2020/2/15 18:32
 **/

public class TokenAuthentication implements Authentication, CredentialsContainer {

    private final AccountInfo info;

    private String credential;

    private boolean authenticated = false;

    public TokenAuthentication(AccountInfo info) {
        this.info = info;
    }

    public TokenAuthentication(AccountInfo info, String credential) {
        this.info = info;
        this.credential = credential;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return info.getAccesses().stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet());
    }

    public void setCredential(String credential) {
        this.credential = credential;
    }

    @Override
    public Object getCredentials() {
        return credential;
    }

    @Override
    public WebDetail getDetails() {
        return WebDetail.builder().ip(info.getIp()).rememberMe(info.getRememberMe()).build();
    }

    @Override
    public Object getPrincipal() {
        return info.getUsername();
    }

    @Override
    public boolean isAuthenticated() {
        return authenticated;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        this.authenticated = isAuthenticated;
    }

    @Override
    public String getName() {
        return info.getUsername();
    }

    @Override
    public void eraseCredentials() {
        credential = null;
    }

    public AccountInfo getAccountInfo() {
        return info;
    }
}
